﻿namespace EasyWeb
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Web.Mvc;
    using EasyWeb.Web.UI;

    [Serializable]
    [ModelBinder(typeof(EWTextModelBinder))]
    public class EWText
    {
        private readonly List<EWTextValue> values = new List<EWTextValue>();

        public IList<EWTextValue> Values
        {
            get { return this.values; }
        }

        public bool HasValue
        {
            get { return HasSpecifiedValue(Thread.CurrentThread.CurrentUICulture.Name); }
        }

        public string GetValue()
        {
            string value;

            if (!TryGetValue(out value))
            {
                throw new InvalidOperationException("The value of the current thread culture does not exist.");
            }

            return value;
        }

        public bool TryGetValue(out string value)
        {
            return TryGetSpecifiedValue(Thread.CurrentThread.CurrentUICulture.Name, out value);
        }

        public bool HasSpecifiedValue(string cultureName)
        {
            EWGuard.IsNotNullOrEmpty("cultureName", cultureName);

            string value;
            return TryGetSpecifiedValue(cultureName, out value);
        }

        public string GetSpecifiedValue(string cultureName)
        {
            EWGuard.IsNotNullOrEmpty("cultureName", cultureName);

            string value;

            if (!TryGetSpecifiedValue(cultureName, out value))
            {
                throw new InvalidOperationException(string.Format("The value of the culture '{0}' does not exist.", cultureName));
            }

            return value;
        }

        public bool TryGetSpecifiedValue(string cultureName, out string value)
        {
            EWGuard.IsNotNullOrEmpty("cultureName", cultureName);

            value = null;

            string culture;
            if (EWResourceCultureHelper.TryGetCultureName(cultureName, out culture))
            {
                var text = this.values.FirstOrDefault(v => StringComparer.OrdinalIgnoreCase.Compare(v.Name, cultureName) == 0);
                if (text != null)
                {
                    value = text.Text;
                    return true;
                }
            }

            return false;
        }
    }
}
